package com.zhilifang.modules.zlf.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhilifang.modules.sys.oauth2.OAuth2Filter;
import com.zhilifang.modules.zlf.entity.Banner;
import com.zhilifang.modules.zlf.entity.FooterType;
import com.zhilifang.modules.zlf.entity.Fslink;
import com.zhilifang.modules.zlf.entity.IdType;
import com.zhilifang.modules.zlf.entity.ImgUpload;
import com.zhilifang.modules.zlf.entity.Information;
import com.zhilifang.modules.zlf.entity.Menu;
import com.zhilifang.modules.zlf.entity.Product;
import com.zhilifang.modules.zlf.service.impl.BannerServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FooterServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FooterTypeServiceImpl;
import com.zhilifang.modules.zlf.service.impl.FslinkServiceImpl;
import com.zhilifang.modules.zlf.service.impl.IndexShowServiceImpl;
import com.zhilifang.modules.zlf.service.impl.InformationServiceImpl;
import com.zhilifang.modules.zlf.service.impl.MenuServiceImpl;
import com.zhilifang.modules.zlf.service.impl.ProductServiceImpl;
import com.zhilifang.modules.zlf.service.impl.SeoServiceImpl;
import com.zhilifang.modules.zlf.utils.Base64EDncrypt;
import com.zhilifang.modules.zlf.utils.PublicMsg;
import com.zhilifang.modules.zlf.utils.Utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Controller 官网首页
 */
@Controller
public class ReceptionIndexController {

	@Autowired
	private MenuServiceImpl menuServiceImpl;
	
	@Autowired
	private BannerServiceImpl bannerServiceImpl ;
	
	@Autowired
	private InformationServiceImpl informationServiceImpl ;
	
	@Autowired
	private FslinkServiceImpl fslinkServiceImpl;
	
	@Autowired
	private FooterServiceImpl footerServiceImpl ;
	
	@Autowired
	private FooterTypeServiceImpl footerTypeServiceImpl;
	
	@Autowired
	private SeoServiceImpl seoServiceImpl ;
	
	@Autowired
    private Configuration configuration;
	
	@Autowired
	private IndexShowServiceImpl indexShowServiceImpl;
	
	@Autowired
	private ProductServiceImpl productServiceImpl ;
	
	
	
	@GetMapping("/index")
	public String gotoReceptionIndex() {
		System.out.println("------------------官网首页------------");
		Map<String, Object> map = new HashMap<>();
		//公共头部页面加载
		publicHeader(map);
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(1));
		//banner图片轮换
		List<Banner> list_1 = bannerServiceImpl.selectBannerListr();
		map.put("str", bannerTp(list_1));
		//首页内容
		map.put("list_1", indexShowServiceImpl.selectListData());
		//核心产品
		map.put("list_2", productServiceImpl.selecProductListr(0));
		//新闻资讯
		List<Information> list_3 =  informationServiceImpl.selectInformationListr(999);
		for(Information list:list_3){
			list.setRelease(Utils.dataStringSub(list.getRelease()));
			list.setContent(Utils.analysisContent(Base64EDncrypt.decryptBASE64(list.getContent())));
		}
		map.put("list_3", list_3);
		//友情链接
		Fslink fslink =new Fslink();
		map.put("list_4", fslinkServiceImpl.selectFslinkListr(fslink));
		//公共底部页面加载
		publicFooter(map);
		 //生成静态页面方法
		createIndexHtml("index_ftl.html", "index.ftl", map); 
		return "reception/index_ftl";
	}
	
	@GetMapping("/jjfa")
	public String gotoReceptionJjfa() {
		System.out.println("------------------解决方案------------");
		Map<String, Object> map = new HashMap<>();
		//公共头部页面加载
		publicHeader(map);
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(2));
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("solve_jjfh_ftl.html", "solve_jjfh.ftl", map);   //生成静态页面方法
		return "reception/solve_jjfh_ftl";
	}
	
	@GetMapping("/cpzx")
	public String gotoReceptionCpzx() {
		System.out.println("------------------产品中心------------");
		Map<String, Object> map = new HashMap<>();
		//公共头部页面加载
		publicHeader(map);
		//SEO
		map.put("seo", seoServiceImpl.selectSeoId(3));
		//核心产品
		map.put("list_2", productServiceImpl.selecProductListr(999));
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("product_ftl.html", "product.ftl", map);   //生成静态页面方法
		return "reception/product_ftl";
	}
	
	@GetMapping("/cpxq/{id}")
	public String gotoReceptionCpxq(@PathVariable(value = "id", required = false) int id) {
		System.out.println("------------------产品详情------------");
		Map<String, Object> map = new HashMap<>();
		//公共头部页面加载
		publicHeader(map);
		map.put("id", id);
		Product result =  productServiceImpl.selectProductById(id);
		result.setContentText(Base64EDncrypt.decryptBASE64(result.getContentText()));  	//解密
		result.setFunctionText(Base64EDncrypt.decryptBASE64(result.getFunctionText()));	//解密
		map.put("result", result);
		//新闻资讯
		List<Information> list_1 = informationServiceImpl.selectInformationListr(2);
		for(Information list:list_1){
			list.setRelease(Utils.dataStringSub(list.getRelease()));
			list.setContent(Utils.analysisContent(Base64EDncrypt.decryptBASE64(list.getContent())));
		}
		map.put("list_1", list_1);
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("product_details_ftl"+id+".html", "product_details.ftl", map);   //生成静态页面方法
		return "reception/product_details_ftl"+id;
	}	

	@GetMapping("/zxzx")
	public String gotoReceptionZxzx() {
		System.out.println("------------------资讯中心------------");
		Map<String, Object> map = new HashMap<>();    
		//公共头部页面加载
		publicHeader(map);
		map.put("seo", seoServiceImpl.selectSeoId(4));
		//列表
		List<Information> list_1 = informationServiceImpl.selectInformationListr(0);
//		String ifStr[] = InformationStr(list_2);		//新闻拼接
		for(Information list:list_1){
			list.setRelease(Utils.dataStringSub(list.getRelease()));
			list.setContent(Utils.analysisContent(Base64EDncrypt.decryptBASE64(list.getContent())));
		}
		map.put("list_1", list_1);
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("news_ftl.html", "news.ftl", map);   //生成静态页面方法
		return "reception/news_ftl";
	}
	
	@GetMapping("/zxxq/{id}")
	public String gotoReceptionZxxq(@PathVariable(value = "id", required = false) int id) {
		System.out.println("------------------资讯详情------------");
		Map<String, Object> map = new HashMap<>();
		//公共头部页面加载
		publicHeader(map);
		map.put("id", id);
		Information  result = informationServiceImpl.selectInformationById(id);
		if(result!=null){
			result.setContent(Base64EDncrypt.decryptBASE64(result.getContent()));
			//内容解密
			map.put("result", result);
			//上一页&下一页初始化
			//首先查询当前分类下的最小和最大id
			List<Information> list_2 = informationServiceImpl.selecUpInDn(result.getInformationTypeId(), id);
			IdType list_1 = informationServiceImpl.selecMinAndMaxId(result.getInformationTypeId());	
			String str[] = new String[4];
			if(list_2.size()==0){
				//上一篇
				str[0]= "已经到底了";
				str[1]= "0";
				//下一篇
				str[2]= "已经到底了";
				str[3]= "0";
			}else if(list_2.size()==1){
				if(id==list_1.getMinid()){
					//上一篇
					str[0]= "已经到底了";
					str[1]= "0";
					//下一篇
					str[2]= list_2.get(0).getName();
					str[3]=list_2.get(0).getId().toString();
					//下一篇
				}else if(id==list_1.getMaxid()){
					//上一篇
					str[0]=  list_2.get(0).getName();
					str[1]= list_2.get(0).getId().toString();
					//下一篇
					str[2]= "已经到底了";
					str[3]= "0";
				}
			}else{
				//上一篇
				str[0]= list_2.get(0).getName();
				str[1]= list_2.get(0).getId().toString();
				//下一篇
				str[2]= list_2.get(1).getName();
				str[3]= list_2.get(1).getId().toString();
				//上一篇
			}
			map.put("str", str);
		}else{
			map.put("result", result);
			String str[] = new String[4];
				//上一篇
				str[0]= "已经到底了";
				str[1]= "0";
				//下一篇
				str[2]= "已经到底了";
				str[3]= "0";
				map.put("str", str);
		}
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("news_details_ftl"+id+".html", "news_details.ftl", map);   //生成静态页面方法
		return "reception/news_details_ftl"+id;
	}
	
	@GetMapping("/gywm")
	public String gotoReceptionGywm() {
		System.out.println("------------------关于我们------------");
		Map<String, Object> map = new HashMap<>();    
		//公共头部页面加载
		publicHeader(map);
		map.put("seo", seoServiceImpl.selectSeoId(5));
		//公共底部页面加载
		publicFooter(map);
		createIndexHtml("about_us_ftl.html", "about_us.ftl", map);   //生成静态页面方法
		return "reception/about_us_ftl";
	}
	
	
	
	
	
	
	@GetMapping("/homePage")
	public String gotoBackstageHomePage() {
		System.out.println("-----------后台框架首页----------");
		return "backstage/index";
	}
	
	@GetMapping("/xpgl")
	public String gotoBackstageXpg() {
		System.out.println("-----------询盘管理----------");
		return "backstage/home";
	}
	
	@GetMapping("/syjj")
	public String gotoBackstageSyjj() {
		System.out.println("-----------首页简介----------");
		return "backstage/brief";
	}
	
	@GetMapping("/fbcp")
	public String gotoBackstageFbcp() {
		System.out.println("-----------发布产品----------");
		return "backstage/product";
	}
	
	@GetMapping("/fbxw")
	public String gotoBackstageFbxw() {
		System.out.println("-----------发布新闻----------");
		return "backstage/news";
	}
	
	@GetMapping("/xxgg")
	public String gotoBackstageXxgg() {
		System.out.println("-----------形象广告----------");
		return "backstage/advert";
	}
	
	@GetMapping("/seoyh")
	public String gotoBackstageSeoyh() {
		System.out.println("-----------SEO优化----------");
		return "backstage/seo";
	}
	
	@GetMapping("/bqgl")
	public String gotoBackstageBqgl() {
		System.out.println("-----------标签管理----------");
		return "backstage/label";
	}
	
	@GetMapping("/yqlj")
	public String gotoBackstageYqlj() {
		System.out.println("-----------友情链接----------");
		return "backstage/blogroll";
	}
	
	@GetMapping("/wzdt")
	public String gotoBackstageWzdt() {
		System.out.println("-----------网站地图----------");
		return "backstage/sitemap";
	}
	
	@GetMapping("/wztj")
	public String gotoBackstageWztj() {
		System.out.println("-----------网站统计----------");
		return "backstage/statistics";
	}
	
	/**
	 * 后台退出。注销session
	 * @return
	 */
	@GetMapping("/logout")
	public String gotoBackstageWztj(HttpSession session) {
		System.out.println("-----------退出----------");
		if(session.getAttribute(OAuth2Filter.SESSION_KEY)!=null){
				session.removeAttribute(OAuth2Filter.SESSION_KEY);
		}
		return "login";
	}
	
	
	/**
	 * 底部公共菜单加载
	 */
	public void publicFooter(Map<String, Object> map){
		System.out.println("------------------公共底部菜单------------");
		List<FooterType> list_1 = footerTypeServiceImpl.selectFooterTypeListr();
		map.put("list_footer_1", list_1);
		for(int i=0;i<list_1.size();i++){
			map.put("footer_"+i, footerServiceImpl.selecFooterListr(list_1.get(i).getId()));
		}
//		createIndexHtml("footer.html", "footer.ftl", map);   //生成静态页面方法
	}
	
	
	/**
	 * 头部公共菜单加载
	 */
	public void publicHeader(Map<String, Object> map){
		System.out.println("------------------公共头部菜单------------");
		List<Menu> list_1 = menuServiceImpl.selectMenuListr();
		map.put("list_header_1", list_1);
//		createIndexHtml("header.html", "header.ftl", map);   //生成静态页面方法
	}
	
	
	
	   /**
     * 首页banner图片html拼接
     * @return
     */
    public String bannerTp(List<Banner> list){
    	 String 	str = "";     //指示符
    	 for(int i=0;i<list.size();i++){
		    if(i==0){
		    	str+="<div class=\"carousel-item active\">";
		    }else{
		    	str+="<div class=\"carousel-item\">";
		    }
		    str+="<img src=\""+list.get(i).getImgurl()+"\" title=\""+list.get(i).getTitle()+"\" alt=\""+list.get(i).getAlt()+"\">";
		    str+="<div class=\"carousel_iCare\">";
		  /*  str+="<div>";
		    str+="<p>加力运动</p>";
		    str+="<p>运动康复系统</p>";
		    str+="</div>";*/
		    str+="<a href=\""+list.get(i).getUrl()+"\">免费试用</a>";
		    str+="</div>";
		    str+="</div>";
    	 }
    	return str;
    }
	
    /**
     * 新闻列表html拼接
     * @return
     */
    public String[] InformationStr(List<Information> list){
    	 String 	str1 = "";     //推荐新闻
    	 String 	str2 = "";     //其他新闻列表
    	 if(list.size()>0){
        	 for(int i=0;i<list.size();i++){
     		    if(i==0||i==1||i==2){
     		    	str1+="<div class=\"news_plan_con w1200\">";
     		    	str1+="<div class=\"news_plan_img clearfloat visible\">";
     		    	str1+="<div>";
     		    	str1+="<a href=\"/zxxq/"+list.get(i).getId()+"\">";
     		    	str1+="<img src=\""+list.get(i).getImgurl()+"\" title=\""+list.get(i).getTitle()+"\" alt=\""+list.get(i).getAlt()+"\">";
     		    	str1+="</a>";
     		    	str1+="</div>";
     		    	str1+="<div class=\"news_right_t\">";
     		    	str1+="<a href=\"/zxxq/"+list.get(i).getId()+"\"><p>"+list.get(i).getName()+"</p>";
     		    	str1+="<span>"+Utils.analysisContentLength(Base64EDncrypt.decryptBASE64(list.get(i).getContent()),110)+"</span></a>";	 	//内容解密
     		    	str1+="</div>";
     		    	str1+="</div>";
     		    	str1+="</div>";
     		    }else{
     		    	str2+="<li>";
     		    	str2+="<a href=\"/zxxq/"+list.get(i).getId()+"\">";
     		    	str2+="<img src=\""+list.get(i).getImgurl()+"\" title=\""+list.get(i).getTitle()+"\" alt=\""+list.get(i).getAlt()+"\">";
     		    	str2+="</a>";
     		    	str2+="</li>";
     		    }
         	 }
    	 }
    	String str[] = {str1,str2};
    	return str;
    }
    
	
	
	
	/**
     * 生成首页静态页面
     * 生成文件名称、调用模板名称、存放数据
     * 
     */
    public void createIndexHtml(String fileName, String ftlName, Map<String, Object> map) {
        try {
            /**获取输出目标文件输出流------开始*/
            String filepath = this.getClass().getResource("/").toURI().getPath()+"views/reception/";
            System.out.println("每次访问新生成的html位置："+filepath);
            File folder = new File(filepath);
            //如果文件夹不存在
            if (!folder.exists()) {
                folder.mkdir();
            }
            File indexHtml = new File(folder, fileName);
            //如果html文件不存在
            if (!indexHtml.exists()) {
                indexHtml.createNewFile();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(indexHtml),"UTF-8"));
            /**获取输出目标文件输出流------结束*/
            //获取模板
            Template template = configuration.getTemplate(ftlName);
            //把数据和输出文件信息交给模板得到静态html文件
            template.process(map,out);
            out.flush();
            out.close();}
        catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
    
    
    @RequestMapping(value = "/ueditor")
    @ResponseBody
    public String ueditor() {
        return PublicMsg.UEDITOR_CONFIG;
    }
    
    /**
	 * 公共接收图片上传
	 * type  文件夹类型
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/imgUpload", method = RequestMethod.POST)
	@ResponseBody
	public ImgUpload imgUpload(@RequestParam("img") MultipartFile list , String type) throws IllegalStateException, IOException{
		ImgUpload result = new ImgUpload();
		String[] data = new String[5];
		if(type==""||type==null){
			type ="index";
		}
		String path = Utils.isLinux(type);  		//判断当前系统类型，根据系统类型存放文件
		//创建图片文件夹存放图片
        File fileDir = new File(path);
        //判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        String fileName = returnPrefixSuffixName(list.getOriginalFilename());
        fileDir = new File(path+fileName);
        list.transferTo(fileDir);//实现文件的上传
		data[0]="/localImg/"+type+"/"+fileName;
        result.setErrno("0");
        result.setData(data);
		return result;
	}
	
	/**
	 * 随机生成文件名称
	 * 名称当前时间+随机数+文件后缀名
	 * 
	 */
	public String returnPrefixSuffixName(String fileName) {
		long time = new Date().getTime() + Math.round(Math.random() * 1000);  //生成随机数
        String prefix = time + "";  //类型转换
		String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
		String suffix =  "."+strArray[suffixIndex];  //生成文件后缀名
		return prefix+suffix;
	}
	
	
	
	
}
